<?php
AppCore::using('XmlRpc_Core');
/**
 * xmlrpc client
 * make calls to remote and
 * parse response
 * @uses XmlRpc_Carrier
 */
class XmlRpc_Client extends XmlRpc_Core
{
    /**
     * the poster
     * @var Util_HttpRequest
     */
    protected $_remote = null;


    /**
     * needs url and token to make calls...
     * @param str $url the url to call
     * @param str $token the token used to encrypt
     */
    public function __construct($url, $token)
    {
        // 5 minutes, enough?
        $this->_remote = new Util_HttpRequest($url, 'POST', 3000);
        $this->_token  = $token;

    }// end __construct


    /**
     * take method calls
     * call remote
     * @param $method the method to call
     * @param $args the params
     * @return mixed the actual class call results in proper array or object form
     */
    public function __call($method, $args = array())
    {
        // first, compose the call...
        $payload = array(
            'method' => $method,
            'args'   => $args
        );

        // set up
        $request = $this->_compose('request', $payload);

        // call and return...
        $this->_remote->setQueryData($request);
        $resp = $this->_remote->send();

        // let's see what's returned...
        if (!empty($resp)) {
            // first, validate if error...
            if (strpos($resp, '<error>') !== false && strpos($resp, '</error>') !== false) {
                // error!
                return $this->_parseError($resp);
            }

            // try putting something nice there...
            $this->_parse($resp);
            // validate...
            if ($this->_mkchecksum($this->_payload, $this->_token) !== $this->_checksum) {
                throw new Exception('DATA INTEGRITY CHECK FAILURE', 300);
            }
            // otherwise, all good...
            return unserialize(base64_decode($this->_payload));
        }

    }// end __call

} // end XmlRpc_Client
?>